package com.king.hive.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

/**
 * 多列
 */
public class MyUDTF2 extends GenericUDTF {

    ArrayList<String> outValue = new ArrayList();

    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {

        // 约束函数返回列的名字
        ArrayList<String> fieldNames = new ArrayList();

        // 约束函数返回列的类型
        ArrayList<ObjectInspector> fieldOIs = new ArrayList();

        fieldNames.add("word");
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
    }

    /**
     * 核心函数处理方法
     * @param objects 传入到函数中的参数
     * @throws HiveException
     */
    @Override
    public void process(Object[] objects) throws HiveException {
        // 处理数据
        String data = objects[0].toString();
        // 分隔符
        String split = objects[1].toString();

        String[] vars = data.split(split);

        for (String var : vars) {
            outValue.clear();
            outValue.add(var);
            forward(outValue);
        }
    }

    /**
     *
     * @throws HiveException
     */
    @Override
    public void close() throws HiveException {

    }
}
